/*
 * @Author: xiaosihan 
 * @Date: 2024-09-16 19:24:56 
 * @Last Modified by: xiaosihan
 * @Last Modified time: 2024-09-22 20:54:56
 */


import { autorun } from "mobx";
import { ReactNode, useEffect, useRef, useState } from "react";
import styles from "./projectDatail.module.less";
import PCHeader from "../PCHeader/PCHeader";
import { useParams } from "react-router-dom";
import { Breadcrumb, Button, Tabs } from "antd";
import hashHistory from "@hashHistory";
import ProjectPartsLibrary from "./ProjectPartsLibrary/ProjectPartsLibrary";
import projectDatailStore from "./projectDatailStore";
import partsApi from "@api/partsApi";
import utilsApi from "@api/utilsApi";
import utils from "@utils";
import { find, get } from "lodash";
import numeral from "numeral";
import uploadProgressModalStore from "../UpdataModel/UploadProgressModal/uploadProgressModalStore";
import thumbRenderer from "../UpdataModel/thumbRenderer";
import UploadProgressModal from "../UpdataModel/UploadProgressModal/UploadProgressModal";
import ProjectJooiner from "./ProjectJoiner/ProjectJoiner";
import projectShareModalStore from "./ProjectJoiner/ProjectShareModal/projectShareModalStore";
import projectPartsLibraryStore from "./ProjectPartsLibrary/projectPartsLibraryStore";
import userStore from "@views/userStore";
import ProjectAnnotations from "./ProjectAnnotations/ProjectAnnotations";
import AllProject from "./AllProject/AllProject";
import allProjectStore from "./AllProject/allProjectStore";
import allfileiconPNG from "./allfileicon.png";

interface Iprops {
    children?: ReactNode
}

// 项目详情
export default function ProjectDatail(props: Iprops) {

    const dom = useRef<HTMLDivElement | null>(null);
    const [data, setData] = useState({});
    const [status, setStatus] = useState("0");
    const params = useParams();
    const [projectId, setProjectId] = useState(projectDatailStore.id);
    const [name, setName] = useState(projectDatailStore.name);
    const [description, setDescription] = useState(projectDatailStore.description);
    const [isSelft, setIsself] = useState(projectDatailStore.userId === userStore.userId);

    useEffect(() => {
        projectDatailStore.setId(params.id || "");
        allProjectStore.setActiveProjectId(params.id || "");
    }, [params]);

    useEffect(() => autorun(() => {
        setProjectId(projectDatailStore.id);
        setName(projectDatailStore.name);
        setDescription(projectDatailStore.description);
        setIsself(projectDatailStore.userId === userStore.userId);
    }), []);

    //上传3d模型
    const updataMadel = async (parame_file?: File) => {
        let file = parame_file || await utils.selectFile(".STEP,.STP,.SLDPRT,.STL,.SAT,.3DXML,.PRT,.ITP,.CATPART,.X_T,.PTC,.X_B,STL,.STP,.PRT,.SLP,.SLDPRT,.STEP,.OBJ,.IGES,.XT,.X_T,.DXF,.SLDASM,.IPT,.GLTF,.GLB,.X_B,.PAR,.GBR,.BRD,.DWFX,.FBX,.zip");

        if (file) {
            // const gltfFile = await utils.to_gltf([file]);
            uploadProgressModalStore.setOpen(true);
            // uploadProgressModalStore.setFormmatConrt(true);
            uploadProgressModalStore.setFileName(file.name);
            await new Promise(resolve => setTimeout(resolve, 100));
            // 格式转换
            // if (file) {
            //     const glbFile = await formatConvert(file, "glb");
            //     file = glbFile;
            // }
            // uploadProgressModalStore.setFormmatConrt(false);

            // 上传文件, 上传缩率图, 获取类型id 同时进行
            const [modelUrl, thumbUrl, typeId] = await Promise.all([
                new Promise<string>(async (resolve, reject) => {
                    const url = await utilsApi.uploadOss(file as File, (progress) => {
                        uploadProgressModalStore.setProgress(Math.min(0.999, progress));
                    });
                    uploadProgressModalStore.setProgress(0.999);
                    resolve(url);
                }),
                new Promise<string>(async (resolve, reject) => {
                    const thumbFile = await thumbRenderer.get_thumb_file(file as File);
                    const thumbUrl = await utilsApi.uploadOss(thumbFile);
                    resolve(thumbUrl);
                }),
                new Promise<string>(async (resolve, reject) => {
                    const modalTypeResult = await partsApi.getModelType();
                    const modalTypeList = get(modalTypeResult, ["data", "data"]);
                    const typeId = get(find(modalTypeList, d => d.name === "3D模型"), ["id"]);
                    resolve(typeId);
                })
            ]);

            const addResult = await partsApi.add(typeId, (file as File).name, modelUrl, thumbUrl, numeral((file as File).size).format('0.0b'), projectId);
            const modelId = get(addResult, ["data", "id"]);
            uploadProgressModalStore.setModelId(modelId);
            uploadProgressModalStore.setProgress(1);

            while (uploadProgressModalStore.open) {
                await new Promise(resolve => requestAnimationFrame(resolve));
            }

            projectPartsLibraryStore.getPartList(projectId);

        }
    }

    return (
        <div ref={dom} className={styles.projectDatail} >
            <PCHeader />

            <div>
                <Breadcrumb
                    className={styles.breadcrumb}
                    items={[
                        {
                            title: <a>项目管理</a>,
                            onClick() {
                                hashHistory.push("/projectCollaboration");
                            }
                        },
                        { title: name, }
                    ]}
                />
            </div>

            <AllProject />
            <div className={styles.container} >
                <div className={styles.title} >{name}</div>
                <div className={styles.describe} >{description}</div>
                <div className={styles.header} >
                    <Tabs
                        activeKey={String(status)}
                        className={styles.tabs}
                        items={[
                            { key: '0', label: '文件' },
                            { key: '1', label: '成员' },
                            { key: '2', label: '批注' },
                        ]}
                        onChange={(v: any) => {
                            setStatus(v);
                        }}
                    />
                    {
                        status === "0" &&
                        <Button
                            type="primary"
                            size="small"
                            onClick={() => {
                                updataMadel()
                            }}
                        >上传文件</Button>
                    }
                    {
                        status === "1" && isSelft &&
                        <Button
                            size="small"
                            className={styles.share}
                            type="primary"
                            onClick={() => {
                                projectShareModalStore.setShow(true);
                                projectShareModalStore.getShareToken(projectId);
                            }}
                        >邀请成员</Button>
                    }

                    <span
                        className={styles.all_file}
                        onClick={() => {
                            hashHistory.push("/partsLibrary")
                        }}
                    >
                        <img
                            alt=""
                            className={styles.icon}
                            src={allfileiconPNG}
                        />
                        所有文件
                    </span>

                </div>

                {/* 项目零件 */}
                {status === "0" && projectId && <ProjectPartsLibrary projectId={projectId} />}
                {status === "1" && projectId && <ProjectJooiner projectId={projectId} />}
                {status === "2" && projectId && <ProjectAnnotations projectId={projectId} />}
            </div>

            <div
                className={styles.thumb}
                ref={dom => thumbRenderer.setContainer(dom)}
            ></div>

            {/* 上传进度弹窗 */}
            <UploadProgressModal />

        </div>
    );

}